package org.springsource.batch;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Component;
import org.springsocial.domain.ExtendedTweet;
import org.springsocial.services.PlayerService;
import org.springsocial.services.TweetService;
import org.springsource.util.ActiveTweeter;

@Component("deleteFilesTasklet")
public class DeleteFilesTasklet implements Tasklet {
	
	private static final Log log = LogFactory.getLog(DeleteFilesTasklet.class);
	@Autowired Twitter twitter;
	@Autowired TweetService tweetService;
	@Autowired PlayerService playerService;
	
	
    public RepeatStatus execute(StepContribution step, ChunkContext chunk)
            throws Exception {
    	log.info("teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
    	System.out.println(System.currentTimeMillis());
    	
    	List<Long> ids = playerService.getPlayerIds(ActiveTweeter.ACTIVE);
    	for (Long id : ids) {
    		List<Tweet> userTimeline = twitter.timelineOperations().getUserTimeline(id);
    		for (Tweet tweet : userTimeline) {
    			System.out.println("player id:"+id);
    			ExtendedTweet tweetById = tweetService.getTweetById(tweet.getId());
	    		if(tweetById == null){
	    			tweetService.saveTweet(buildExtendedTweet(tweet));
	    		}
			}
	    		
		}
    	
        Map<String, Object> params = chunk.getStepContext().getJobParameters();
        log.info("path"+params.get("path"));
        log.info("age"+params.get("age"));
        return RepeatStatus.FINISHED;
    }
    private ExtendedTweet buildExtendedTweet(Tweet tweet){
		ExtendedTweet extTweet = new ExtendedTweet();
		extTweet.setCreatedAt(tweet.getCreatedAt());
		extTweet.setFromUser(tweet.getFromUser());
		extTweet.setFromUserId(tweet.getFromUserId());
		extTweet.setId(tweet.getId());
		extTweet.setInReplyToStatusId(tweet.getInReplyToStatusId());
		extTweet.setLanguageCode(tweet.getLanguageCode());
		extTweet.setProfileImageUrl(tweet.getProfileImageUrl());
		extTweet.setRetweetCount(tweet.getRetweetCount());
		extTweet.setSource(tweet.getSource());
		extTweet.setText(tweet.getText());
		extTweet.setToUserId(tweet.getToUserId());
		return extTweet;
	}

}
